package edu.njust.underwater.config;

import edu.njust.underwater.exception.ResponseException;
import edu.njust.underwater.exception.ViewException;
import edu.njust.underwater.pojo.User;
import edu.njust.underwater.utils.ContextUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();     // 路径匹配器

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // 获取请求路径
        String uri = request.getRequestURI();
        // 不拦截的请求
        String[] urls = new String[] {
                "/img/**",
                "/js/**",
                "/css/**",
                "/",
                "/login",
                "/error/**",
                "/register",
                "/**/*.html",
                "/comments/*",
                "/sortComments/*"
        };

        if (!check(urls, uri)) {
            User user = (User) request.getSession().getAttribute("user");
            if (user != null) {
                ContextUtils.setUser(user);
                return true;
            }

            log.warn("拦截请求：{}", uri);
            throw new ResponseException("用户未登录");
        }

        return true;
    }


    public boolean check(String[] uris, String requestURI) {
        for (String uri : uris) {
            boolean match = PATH_MATCHER.match(uri, requestURI);    // 判断路径是否匹配
            if (match) {
                return true;
            }
        }
        return false;
    }
}
